package com.xdth.mq.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dy on 17-5-19.
 */
public abstract class MqConsumer {

  public final Logger logger = LoggerFactory.getLogger(this.getClass());

  public abstract JmsTemplate getTemplate();

  public Map<String, Object> receiveMap(String destinationName) {
    Map<String, Object> map = new HashMap<>();
    MapMessage message = (MapMessage) getTemplate().receive(destinationName);
    try {
      Enumeration<String> en = message.getMapNames();
      if (null != en) {
        while (en.hasMoreElements()) {
          String key = en.nextElement();
          map.put(key, message.getObject(key));
        }
      }
    } catch (JMSException e) {
      logger.error("接受消息队列MAP信息[{}]失败", destinationName, e);
    }
    return map;
  }

  public Map<String, Object> receiveText(String destinationName) {
    TextMessage message = (TextMessage) getTemplate().receive(destinationName);
    Map<String, Object> map = new HashMap<>();
    try {
      System.out.println(message.getPropertyNames());
      Enumeration<String> propertyNames = message.getPropertyNames();
      if (null != propertyNames) {
        while(propertyNames.hasMoreElements()) {
          String key = propertyNames.nextElement();
          map.put(key, message.getObjectProperty(key));
        }
      }

      map.put("TEXT", message.getText());
    } catch (JMSException e) {
      logger.error("接受消息队列TEXT信息[{}]失败", destinationName, e);
    }
    return map;
  }

  public Serializable receiveObject(String destinationName) {
    ObjectMessage message = (ObjectMessage) getTemplate().receive(destinationName);

    try {
      Serializable s = message.getObject();
      return s;
    } catch (JMSException e) {
      logger.error("接受消息队列OBJECT信息[{}]失败", destinationName, e);
    }
    return null;
  }
}
